<template>
  <div class="instrument-page">
    <!-- 顶部工具栏 -->
    <div style="margin-bottom: 12px;">
      <el-button type="primary" @click="openCreateDialog">新增仪器</el-button>
<!--      <el-input-->
<!--          v-model="search"-->
<!--          placeholder="搜索仪器名称"-->
<!--          style="width: 300px; margin-left: 12px;"-->
<!--          clearable-->
<!--      />-->
    </div>

    <!-- 表格 -->
    <el-table :data="instrumentList" border style="width: 100%;">
      <el-table-column label="序号" prop="id" width="80"/>
      <el-table-column label="名称" prop="name"/>
      <el-table-column label="房间序号" prop="roomId"/>
      <el-table-column label="类型" :formatter="formatType"/>
      <el-table-column label="二级类型" :formatter="formatSubType"/>
      <el-table-column label="消耗积分" prop="pointsCost" width="100"/>
      <el-table-column label="可预约" prop="available" width="80">
        <template #default="{ row }">
          <el-tag type="success" v-if="row['available']">是</el-tag>
          <el-tag type="info" v-else>否</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300px">
        <template #default="{ row }">
          <el-button size="small" @click="showRoleDialog(row)">分配权限</el-button>
          <el-button size="small" @click="viewQRCode(row)">二维码</el-button>
          <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteInstrumentHandler(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        @current-change="fetchInstruments"
        layout="total, prev, pager, next"
        background
        style="margin-top: 16px"
    />

    <!-- 新增/编辑 弹窗 -->
    <el-dialog :model-value="showDialog" @update:model-value="closeDialog" :title="form.id ? '编辑仪器' : '新增仪器'" width="500px">
      <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
        <el-form-item label="仪器名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="仪器房间" prop="roomId">
          <el-input-number v-model="form.roomId" :min="1" />
        </el-form-item>
        <el-form-item label="仪器类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="科研仪器" value="1" />
            <el-option label="教学仪器" value="2" />
            <el-option label="通用仪器" value="3" />
            <el-option label="专用仪器" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="子类型" prop="subType">
          <el-select v-model="form.subType" placeholder="请选择子类型">
            <el-option
                v-for="item in subTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可被预约">
          <el-switch v-model="form.available" />
        </el-form-item>
        <el-form-item label="积分消耗" prop="pointsCost">
          <el-input-number v-model="form.pointsCost" :min="0" />
        </el-form-item>
        <el-form-item label="照片" prop="imgName">
          <el-upload
              :auto-upload="false"
              :limit="1"
              list-type="picture-card"
              :on-change="handleImageChange"
              :file-list="uploadFileList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="qr" style="width: 200px">
      <qrcode-vue
          :value="qrContent"
          :size="100"
          title="仪器二维码"
      />
    </el-dialog>
  </div>

  <RoleDialog v-model="roleDialog" :type="type" :resourceIndex="resourceIndex" @close="closeRoleResourceAdd"/>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/apps/admin/utils/request.js'
import {
  getInstruments,
  deleteInstrument,
  createInstrument,
  updateInstrument,
  getInstrumentSubTypes
} from '@/apps/admin/utils/instrumentApi.js'
import QrcodeVue from "qrcode.vue";
import RoleDialog from "@/apps/admin/components/RoleDialog.vue";

const type = ref()
const resourceIndex = ref()
const roleDialog = ref(false)
function closeRoleResourceAdd(){
  roleDialog.value = false;
}
function showRoleDialog(q){
  type.value = "INSTRUMENT"
  resourceIndex.value = q.id
  roleDialog.value = true;
}

const uploadFileList = ref([])

const qr = ref(false)
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)

const instrumentList = ref([])
const showDialog = ref(false)
const formRef = ref()

const subTypes = ref([])
const form = ref({
  id: null,
  name: '',
  roomId: null,
  type: '',
  subType: '',
  available: true,
  pointsCost: 0,
  imgName: ''
})

const rules = {
  name: [{ required: true, message: '请输入仪器名称', trigger: 'blur' }],
  roomId: [{ required: true, type: 'number', message: '请输入房间号', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  subType: [{ required: true, message: '请选择子类型', trigger: 'change' }],
  pointsCost: [
    { required: true, type: 'number', message: '请输入积分', trigger: 'blur' },
    { type: 'number', min: 0, message: '积分不能为负数', trigger: 'blur' }
  ],
  imgName: [{ required: true, message: '请上传图片', trigger: 'change' }]
}

const fetchInstruments = () => {
  getInstruments({
    page: currentPage.value,
    size: pageSize.value,
    keyword: search.value
  }).then(res => {
    instrumentList.value = res.data.records
    totalItems.value = res.data.total
  })
}

const openCreateDialog = () => {
  form.value = {
    id: null,
    name: '',
    roomId: null,
    type: '',
    subType: '',
    available: true,
    pointsCost: 0,
    imgName: ''
  }

  showDialog.value = true
}

const openEditDialog = (row) => {
  form.value = { ...row }
  if (row.imgName) {
    uploadFileList.value = [
      {
        name: row.imgName,
        url: "/api/src/img/" + row.imgName,
        status: 'finished',
        uid: '-1'
      }
    ]
  } else {
    uploadFileList.value = []
  }
  showDialog.value = true
}

const closeDialog = () => {
  showDialog.value = false
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    const action = form.value.id ? updateInstrument : createInstrument
    const result = await action(form.value)

    if (result.code === 200) {
      ElMessage.success(form.value.id ? '编辑成功' : '创建成功')
      showDialog.value = false
      fetchInstruments()
    } else {
      ElMessage.error(result.msg || '操作失败')
    }
  })
}

const handleImageChange = async (uploadFile) => {
  const file = uploadFile.raw
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error("图片不能超过 2MB")
    return
  }

  const formData = new FormData()
  formData.append('file', file)

  try {
    const res = await request.post('/v1/admin/uploadImg', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    form.value.imgName = res.data.url
  } catch {
    ElMessage.error('图片上传失败')
  }
}

const deleteInstrumentHandler = async (row) => {
  await deleteInstrument({id: row.id})
  ElMessage.success('删除成功')
  await fetchInstruments()
}

const qrContent = ref("");
const viewQRCode = (row) => {
  console.log('查看二维码:', row)
  qrContent.value = JSON.stringify({
    "instrumentId": row.id,
    "instrumentName": row.name
  })
  qr.value = true;

}

const formatType = (row) => {
  switch (row.type) {
    case 1:
      return '科研仪器'
    case 2:
      return '教学仪器'
    case 3:
      return '通用仪器'
    case 4:
      return '专用仪器'
    default:
      return '未知类型'
  }
}



const formatSubType = (row) => {
  const type = subTypes.value.find(item => item.id === row.subType)
  return type?.name || row.subType
}

watch(search, () => {
  currentPage.value = 1
  fetchInstruments()
})

onMounted(async () => {
  const res = await getInstrumentSubTypes()
  subTypes.value = res.data
  fetchInstruments()
})
</script>
